package north

import (
	"errors"
	"fmt"
	"iot-base/common/config"
	"iot-base/common/ctrltype"
	mqtt "iot-base/common/mqtt"
	"iot-base/common/notify"
	"sync"
	"time"
)

func handleCtrl(client mqtt.IOTMQTTBroker, topic string, pCmd *mqtt.Cmd) {
	if pCmd != nil && pCmd.Body != nil {
		ctrlCmd, ok := pCmd.Body.(*ctrltype.CtrlCmd)
		fmt.Println("&&&&&&*****************handlectrl-------", ctrlCmd, ok)
		if ok && ctrlCmd != nil {
			notify.Ctrl(ctrlCmd, 10*time.Second, func(pResult *ctrltype.CtrlResult) {
				var code = 0
				var errInfo = ""
				if pResult.Error != nil {
					code = -1
					errInfo = pResult.Error.Error()
				}
				client.Reply(config.GetCloudTopic(), pCmd, code, errInfo, pResult.Result)
			}, false)
		}
	}
}

func handleCmd(client mqtt.IOTMQTTBroker, topic string, pCmd *mqtt.Cmd) {

}

var mapHandler map[string]func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error)
var m *sync.RWMutex

//var handlerMapChan chan *ctrltype.CtrlCmd
func init() {
	//handlerMapChan = make(chan *ctrltype.CtrlCmd)
	m = new(sync.RWMutex)
	mapHandler = make(map[string]func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error))
	notify.SubCtrlCmd("IOTBASEmEdgeCTL", func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error) {
		fmt.Println("----------get ctrl cmd------------------edgectrl")
		if pCmd != nil {
			m.RLock()
			fun := mapHandler[pCmd.ID]
			m.RUnlock()
			if fun != nil {
				fmt.Println("run---------------------------registered fun------------")
				return fun(pCmd)
			}

		}
		return nil, errors.New("callback not found")
	})

}

//RegisterCtrlFun 注册回调函数
func RegisterCtrlFun(ctrlCmdID string, fun func(pCmd *ctrltype.CtrlCmd) (map[string]interface{}, error)) {
	m.Lock()
	mapHandler[ctrlCmdID] = fun
	m.Unlock()
}
